import { useEffect, useState, useMemo } from "react";  
import { Component, useComponentStore, getComponentById } from "../../editor/stores/components";
import { Dropdown, Popconfirm, Space } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
// import { createPortal } from 'react-dom'; // 类似 Vue 的 teleport 传送门，将元素挂载到指定节点

interface SelectedMaskProps {
    containerClassName: string;
    componentId: string;
}

export function SelectedMask({ containerClassName, componentId }: SelectedMaskProps){
    const { components, curComponentId, curComponent, setCurComponentId , deleteComponent } = useComponentStore()

    const [position, setPostion] = useState({
        left: 0,
        top: 0,
        width: 0,
        height: 0,
    })

    useEffect(() => {
        updatePosition()
    }, [componentId]) // 这里的 componentId 是 curComponentId 的值传过来的


    useEffect(() => {
        // 加延迟是因为 components 改变宽高属性的话，到渲染完成，
        // 中间在拿到 getBoundingClientRect 改变后的宽高是有一段时间的。
        setTimeout(() => {
            updatePosition()
        }, 200)
    }, [components])

    useEffect(() => {
        const resizeHandler = () => {
            updatePosition()
        }
        window.addEventListener('resize', resizeHandler)
        return () => {
            window.removeEventListener('resize', resizeHandler)
        }
    }, [])


    const parentComponents = useMemo(() => {
        const parentComponents: Component[] = []
        if (curComponentId) {
            let component = curComponent
            while(component?.parentId) {
                component = getComponentById(component.parentId, components)
                if(component) {
                    parentComponents.push(component)
                }
            }
        }
        return  parentComponents
    }, [curComponentId])

    function updatePosition(){
        if (!componentId) return 
        const container = document.querySelector(`.${containerClassName}`)
        if (!container) return

        const component = document.querySelector(`[data-component-id="${componentId}"]`)
        if (!component) return

        const { left, top, width, height } = component.getBoundingClientRect()
        const { left: containerLeft, top: containerTop } = container.getBoundingClientRect()

        setPostion({
            left: left - containerLeft + container.scrollLeft,
            top: top - containerTop + container.scrollTop,
            width,
            height,
        })
    }

    function handleDelete(){
        if (curComponentId) {
            deleteComponent(curComponentId)
            setCurComponentId(null)
        }
    }

    return (
        // 遮罩层
        <div
            className="selected-mask"
            style={{
                position: 'absolute',
                zIndex: 13,
                left: position.left,
                top: position.top,
                width: position.width,
                height: position.height,
                border: '1px dashed blue',
                backgroundColor: 'rgba(0, 0, 255, 0.1)',
                borderRadius: 4,
                boxSizing: 'border-box',
                pointerEvents: 'none',
            }}
        >
                {/* 操作栏 */}
                <div
                    className="selected-mask__content"
                    style={{
                        position: 'absolute',
                        zIndex: 12,
                        right: 0,
                        top: position.top <= 0 ? 0 : -22,
                        color: '#fff',
                        padding: '2px 5px',
                        borderRadius: '3px',
                        fontSize: '12px',
                        display: 'inline-block',
                        pointerEvents: 'all',
                    }}
                >
                    <Space>
                        <Dropdown
                            menu={{
                                items: parentComponents.map((item) => ({
                                    key: item.id,
                                    label: item.name,
                                })),
                                onClick: ({ key }) => {
                                    setCurComponentId(key)
                                }
                            }}
                            disabled={parentComponents.length === 0}
                         >
                            <div 
                                style={{
                                    padding: '0 8px',
                                    backgroundColor: 'blue',
                                    borderRadius: 4,
                                    color: '#fff',
                                    cursor: "pointer",
                                    whiteSpace: 'nowrap',
                                }}
                            >
                                { curComponent?.desc }
                            </div>
                         </Dropdown>

                        { curComponentId !== "1" && (
                        <div
                            style={{
                                padding: "0 8px",
                                backgroundColor: 'blue',
                            }}
                        >
                            <Popconfirm
                                title="确定删除?"
                                okText="确定"
                                cancelText="取消"
                                onConfirm={handleDelete}
                            >
                                <DeleteOutlined style={{ color: '#fff' }}/>
                            </Popconfirm>
                        </div>
                        )}
                    </Space>
                </div>

        </div>
    )
 }